package com.gframework.autoconfigure;

import java.util.List;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;

/**
 * mybatis plugin插件配置辅助操作抽象父类.
 * 
 * @since 2.0.0
 * @author Ghwolf
 */
abstract class AbstractMybatisPluginConfiguration implements InitializingBean {

    @Autowired
    protected List<SqlSessionFactory> sqlSessionFactoryList;
    
    @Override
    public void afterPropertiesSet() throws Exception {
    	Interceptor plugin = this.getPlugin();
    	if (plugin == null) {
    		return ;
    	}
    	
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            if(!sqlSessionFactory.getConfiguration().getInterceptors().contains(plugin)){
            	sqlSessionFactory.getConfiguration().addInterceptor(plugin);
            }
        }
    }
    
    /**
     * 获取插件对象，只会获取一次
     * @return 返回mybatis插件对象，如果返回null，则忽略此插件
     */
    @Nullable
    protected abstract Interceptor getPlugin();
    
}
